package com.sword.demo.quartz.service.impl;

import com.sword.demo.quartz.service.SchedulerService;
import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.MethodInvoker;

import java.lang.reflect.InvocationTargetException;

/**
 * 定时任务-服务实现类
 * @author sword
 * @date 2022/11/28 17:29
 */
@Service
@RequiredArgsConstructor
public class SchedulerServiceImpl implements SchedulerService {
    /**
     * 定时任务总控制器
     */
    private final Scheduler scheduler;

    /**
     * Spring上下文
     */
    private final ApplicationContext context;

    @Override
    public void invokeJobDetail(String jobDetailId) throws InvocationTargetException, IllegalAccessException {
        /*
         * 根据指定定时任务详情bean的id获取该bean
         * 因为定时任务详情配置的都是FactoryBean，所以需要添加前缀&来直接获取该bean的MethodInvoker接口，
         * 而不是使用FactoryBean的getObject方法获取到的JobDetail
         * 获取到定时任务详情后执行该任务
         */
        ((MethodInvoker) context.getBean("&" + jobDetailId)).invoke();
    }

    @Override
    public void start() throws SchedulerException {
        scheduler.start();
    }

    @Override
    public void standby() throws SchedulerException {
        scheduler.standby();
    }

    @Override
    public void shutdown() throws SchedulerException {
        scheduler.shutdown();
    }
}
